package wykop.download;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.List;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;

public class ProxyList {

	private static boolean checkWithGoogle(final Proxy proxy) {
		try {
			final URL url = new URL("http://www.google.pl");
			final HttpURLConnection connection = (HttpURLConnection) url
					.openConnection(proxy);
			connection.setRequestMethod("GET");
			connection.setReadTimeout(10000);
			connection.setConnectTimeout(10000);
			connection.connect();

			final int status = connection.getResponseCode();

			if (status == HttpURLConnection.HTTP_OK) {
				final InputStream is = connection.getInputStream();
				final Response response = new Response(status, is);
				return true;
			}

			return false;
		} catch (final Exception e) {
			return false;
		}
	}

	private static boolean checkWithWykop(final Proxy proxy) {
		try {
			final URL url = new URL("http://www.wykop.pl/link/2");
			final HttpURLConnection connection = (HttpURLConnection) url
					.openConnection(proxy);
			connection.setRequestMethod("GET");
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
			connection.connect();
			final int status = connection.getResponseCode();

			if (status == HttpURLConnection.HTTP_OK) {
				final InputStream is = connection.getInputStream();
				final Response response = new Response(status, is);
				return true;
			}

			return false;
		} catch (final Exception e) {
			return false;
		}
	}

	public static List<Proxy> load() {
		try {
			final InputStream is = ProxyList.class
					.getResourceAsStream("proxyList.txt");
			final BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			final List<Proxy> proxies = Lists.newArrayList();
			String line = null;

			while ((line = reader.readLine()) != null) {

				if (!Strings.isNullOrEmpty(line)) {

					final Proxy proxy = parseProxy(line);
					proxies.add(proxy);
				}
			}

			return proxies;
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}

	}

	private static Proxy parseProxy(final String line) {
		final String[] splitted = line.split(":");
		final String host = splitted[0];
		final int port = Integer.parseInt(splitted[1]);
		return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));

	}

}
